package com.blog.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SensitiveFilter {

    // 替换符
    private static final String REPLACEMENT = "*";

    // 根节点
    private TrieNode rootNode = new TrieNode();

    // 当该类被初始化时，自动调用
    @PostConstruct
    public void init() {
        try(
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ) {
            String keyWord;
            while ((keyWord = reader.readLine()) != null) {

            }
        } catch (IOException e) {
            log.error("加载敏感词失败：" + e.getMessage());
        }
    }

    /**
     * 将一个敏感词添加到前缀树中去
     */
    private void addKeyWord() {

    }

    /**
     * 前缀树节点
     */
    private class TrieNode {
        //关键词结束标志
        private boolean isKeyWordEnd = false;

        //子节点 key是下级字符，value是下级节点
        private Map<Character, TrieNode> subNodes = new HashMap<>();

        public boolean isKeyWordEnd() {
            return isKeyWordEnd;
        }

        public void setKeyWordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }

        // 添加子节点
        public void addSubNode(Character c, TrieNode node) {
            subNodes.put(c, node);
        }

        // 获取子节点
        public TrieNode getSubNode(Character c) {
            return subNodes.get(c);
        }
    }
}
